﻿<?php

namespace app\api\library;
use think\Env;
class Wechat
{
    private $appid;
    private $appserct;
    public $url;//回调地址

    //利用构造函数初始化
    public function __construct()
    {
        $this->appid = 'wxf08c56ad4c545275';
        $this->appserct = '2f313021e6b047bd9df29022abec9c79';

    }

    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    //获取code值
    public function getcode($code)
    {
        if (!isset($code)) {
            $urls = $this->url;
            $url = urlencode($urls);
            $state = $_GET['LockNum']?$_GET['LockNum']:'STATE';
            $gcodeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect";
            // $gcodeurl="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$url}&response_type=code&scope=snsapi_base&state=$state#wechat_redirect";
            //header("loction:{$gcodeurl}");
            echo "<script language=\"javascript\">";
            echo "document.location='" . $gcodeurl . "'";
            echo "</script>";

            die();
        } else {
            return $code;
        }
    }

    //获取access_token和openid值
    public function getopenid($code)
    {
        $gopenidurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appserct}&code={$this->getcode($code)}&grant_type=authorization_code";

        $access_arr = $this->https_request($gopenidurl);
        $array = json_decode($access_arr, true);
        //$access_token=$array['access_token'];
        //$openid=$array['openid'];
        return $array;
    }


    public function getuser($array)
    {  //传入getopenid()获取到的值

        $access_token = $array['access_token'];
        $openid = $array['openid'];


        $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}";
        $user_list = $this->https_request($url2);
        $user = json_decode($user_list, true);

        return $user; //用户信息。数组格式

    }


}

?>
